package com.whq.security.context;

import org.springframework.util.StringUtils;

public class DataContextHolder {

    public static final String MODE_THREADLOCAL = "MODE_THREADLOCAL";

    public static final String MODE_INHERITABLETHREADLOCAL = "MODE_INHERITABLETHREADLOCAL";

    public static final String MODE_GLOBAL = "MODE_GLOBAL";

    private static DataContextHolderStrategy strategy;

    private static String strategyName = "";

    private static int initializeCount = 0;

    static {
        initialize();
    }

    public Object getContext() {
        return strategy.getContext();
    }

    public void setContext(Object context) {
        strategy.setContext(context);
    }

    public void clearContext() {
        strategy.clearContext();
    }

    private static void initialize() {
        if (!StringUtils.hasText(strategyName)) {
            strategyName = MODE_THREADLOCAL;
        }

        if (strategyName.equals(MODE_THREADLOCAL)) {
            strategy = new ThreadLocalDateContextHolderStrategy();
        } else if (strategyName.equals(MODE_INHERITABLETHREADLOCAL)) {
            strategy = new InheritableThreadLocalDataContextHolderStrategy();
        } else if (strategyName.equals(MODE_GLOBAL)) {
            strategy = new GlobalDataContextHolderStrategy();
        }
        initializeCount++;
    }

    public static String getStrategyName() {
        return strategyName;
    }

    public static void setStrategyName(String strategyName) {
        DataContextHolder.strategyName = strategyName;
        initialize();
    }

    @Override
    public String toString() {
        return "DataContextHolder[strategy='" + strategyName + "'; initializeCount=" + initializeCount + "]";
    }
}
